package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.event.EMMessageEvent;
import com.cljz.makepassenger.model.net.bean.NoticeListBean;
import com.cljz.makepassenger.present.activity.GroupListP;
import com.cljz.makepassenger.utils.L;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMConversationListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.jakewharton.rxbinding.view.RxView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;


/**
 * Created by apple on 2017/5/11.
 */

public class GroupListActivity extends BaseActivity<GroupListP> implements EMConnectionListener {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.fl_back)
    FrameLayout flBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.fl_title_right)
    FrameLayout flTitleRight;
    @BindView(R.id.iv_title_right1)
    ImageView ivTitleRight1;
    @BindView(R.id.fl_title_right1)
    FrameLayout flTitleRight1;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.ecl_group)
    EaseConversationList eclGroup;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.btn_empty)
    Button btnEmpty;
    @BindView(R.id.rl_empty)
    RelativeLayout rlEmpty;
    private List<EMConversation> emConversationList;
    private ImageView ivMsgHint;
    private TextView tvMsgTitle;
    private TextView tvMsgDes;
    private TextView tvMsgTime;
    private ArrayList<NoticeListBean.DataBeanX> noticeList;

    final RefreshHandle handler = new RefreshHandle(this);
    private View view;

    @Override
    public void initData(Bundle savedInstanceState) {
        noticeList = (ArrayList<NoticeListBean.DataBeanX>) getIntent().getExtras().getSerializable("noticeList");
        tvEmpty.setText("您当前还未收到消息");
        rlEmpty.setVisibility(View.GONE);
        tvTitleName.setText("消息");
        initHead();
        setUpView();
    }

    private void initHead() {
        View headView = View.inflate(this, R.layout.item_group_list_head, null);
        ivMsgHint = (ImageView) headView.findViewById(R.id.iv_msg_hint);
        tvMsgTitle = (TextView) headView.findViewById(R.id.tv_msg_title);
        tvMsgDes = (TextView) headView.findViewById(R.id.tv_msg_des);
        tvMsgTime = (TextView) headView.findViewById(R.id.tv_msg_time);
        if (noticeList != null && noticeList.size() > 0) {
            ivMsgHint.setVisibility("0".equals(noticeList.get(0).getIs_read()) ? View.VISIBLE : View.GONE);
            tvMsgDes.setText(noticeList.get(0).getMsg());
            tvMsgTime.setText(noticeList.get(0).getAdd_time());

        } else {
            ivMsgHint.setVisibility(View.GONE);
        }
        eclGroup.addHeaderView(headView);

    }

    private void setUpView() {
        EMClient.getInstance().addConnectionListener(this);
        emConversationList = new ArrayList<>();
        emConversationList.addAll(loadConversationList());
//        if (noticeList != null) {
//            if (emConversationList.size() == 0 && noticeList.size() == 0) {
//                rlEmpty.setVisibility(View.VISIBLE);
//                eclGroup.setVisibility(View.GONE);
//            } else {
//                rlEmpty.setVisibility(View.GONE);
//                eclGroup.setVisibility(View.VISIBLE);
//
//            }
//        } else {
//            if (emConversationList.size() == 0) {
//                rlEmpty.setVisibility(View.VISIBLE);
//                eclGroup.setVisibility(View.GONE);
//
//            } else {
//                rlEmpty.setVisibility(View.GONE);
//                eclGroup.setVisibility(View.VISIBLE);
//
//            }
//        }
        eclGroup.init(emConversationList);
        handler.sendMessageDelayed(Message.obtain(), 500);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        EMClient.getInstance().removeConnectionListener(this);
    }

    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(btnEmpty)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .putInt("type", EditorInvitedActivity.EDITOR_INVITE)
                                .to(EditorInvitedActivity.class)
                                .launch();
                    }
                });
        RxView.clicks(flBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(MainActivity.class)
                                .launch();
                    }
                });
        eclGroup.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showDeleteWindow(view, position);
                return true;
            }
        });
        eclGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    Router.newIntent((Activity) App.getInstance())
                            .putSerializable("noticeList", noticeList)
                            .to(SystemMsgActivity.class)
                            .launch();
                    ivMsgHint.setVisibility(View.GONE);
                } else {
                    EMConversation conversation = eclGroup.getItem(position - 1);
                    String username = conversation.conversationId();
                    if (username.equals(EMClient.getInstance().getCurrentUser()))
                        Toast.makeText(GroupListActivity.this, R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                    else {
                        // start chat acitivity
                        view.findViewById(R.id.unread_msg_number).setVisibility(View.GONE);
                        Intent intent = new Intent(GroupListActivity.this, ChatActivity.class);
                        if (conversation.isGroup()) {
                            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                                // it's group chat
                                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_CHATROOM);
                            } else {
                                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                            }

                        }
                        // it's single chat
                        intent.putExtra(EaseConstant.EXTRA_USER_ID, username);
                        startActivity(intent);
                    }
                }
            }
        });

    }

    private void showDeleteWindow(View v, final int position) {
        view = v.findViewById(R.id.message);
        final PopupMenu menu = new PopupMenu(this, view);

        menu.getMenuInflater().inflate(R.menu.group_list_menu, menu.getMenu());
        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (position == 0) return false;
                EMConversation conversation = eclGroup.getItem(position - 1);
                if (conversation.getType() == EMConversation.EMConversationType.GroupChat) {
                    String username = conversation.conversationId();
                    String owner = EMClient.getInstance().groupManager().getGroup(username).getOwner();
                    if (owner.equals(getP().getLocalUserInfo(getP().getToken()).getEid())) {
                        showToast("群主不能删除群聊", R.mipmap.jinshi);

                    } else {
                        try {
                            // delete conversation
                            EaseAtMessageHelper.get().removeAtMeGroup(conversation.conversationId());
                            EMClient.getInstance().chatManager().deleteConversation(conversation.conversationId(), false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                menu.dismiss();
                refresh();
                return true;
            }
        });
        menu.show();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_group_list;
    }

    @Override
    public GroupListP newP() {
        return new GroupListP();
    }


    protected List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);

        }
        Log.e("EMConversation", list.size() + "");
        return list;
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }


    protected EMConversationListener convListener = new EMConversationListener() {

        @Override
        public void onCoversationUpdate() {
            refresh();
        }

    };

    public void refresh() {
        L.e("refresh");
        emConversationList.clear();
        emConversationList.addAll(loadConversationList());
//        if (noticeList != null) {
//            if (emConversationList.size() == 0 && noticeList.size() == 0) {
//                rlEmpty.setVisibility(View.VISIBLE);
//                eclGroup.setVisibility(View.GONE);
//            } else {
//                rlEmpty.setVisibility(View.GONE);
//                eclGroup.setVisibility(View.VISIBLE);
//            }
//        } else {
//            if (emConversationList.size() == 0) {
//                rlEmpty.setVisibility(View.VISIBLE);
//                eclGroup.setVisibility(View.GONE);
//            } else {
//                rlEmpty.setVisibility(View.GONE);
//                eclGroup.setVisibility(View.VISIBLE);
//
//            }
//        }
        eclGroup.refresh();
    }

    @Override
    public void onConnected() {
        refresh();
    }

    @Override
    public void onDisconnected(int i) {
        refresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Router.newIntent((Activity) App.getInstance())
                    .to(MainActivity.class)
                    .launch();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private static class RefreshHandle extends Handler {
        private final WeakReference<GroupListActivity> mActivity;

        RefreshHandle(GroupListActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            GroupListActivity activity = mActivity.get();
            activity.refresh();
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Override
    public void bindEvent() {
        super.bindEvent();
        BusProvider.getBus().toObservable(EMMessageEvent.class)
                .compose(this.<EMMessageEvent>bindToLifecycle())
                .subscribe(new Action1<EMMessageEvent>() {
                    @Override
                    public void call(EMMessageEvent emMessageEvent) {
                        refresh();
                        L.e("emmessagerefresh");
                    }
                });
    }
}
